<?php
// +----------------------------------------------------------------------
// | ManniuRead
// +----------------------------------------------------------------------
// | Copyright (c) 2006~2016 http://manniuyun.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: heitao <read@manniuyun.com>
// +----------------------------------------------------------------------

namespace app\mall\model;

use think\Model;
use app\mall\model\MallSpecGroups as MallSpecGroupsModel;
use app\mall\model\MallSpecItems as MallSpecItemsModel;

class MallSpecCats extends Model{
	/**
     * 更新缓存
     * @access public
     * @return void
     */
    public function cache() {
        cache('mall_goods_specs',NULL);
        // 获取所有规格分类
        $spec_cats = $this->select();
        $spec_cats = $spec_cats ? $spec_cats : [];
        $spec_groups = MallSpecGroupsModel::all();
        $spec_groups = $spec_groups ? $spec_groups : [];
        $spec_items = MallSpecItemsModel::all();
        $spec_items = $spec_items ? $spec_items : [];
        $mall_goods_specs = [];
        // 规格归类
        foreach ($spec_cats as $cat) {
        	$mall_goods_specs[$cat->getData('id')] = $cat->getData();
        	foreach ($spec_groups as $group) {
        		if($group->getData('spec_catid') == $cat->getData('id')){
        			$mall_goods_specs[$cat->getData('id')]['groups'][$group->getData('id')] = $group->getData();
	        		foreach ($spec_items as $item) {
	        			if($item->getData('spec_group_id') == $group->getData('id')){
	        				$mall_goods_specs[$cat->getData('id')]['groups'][$group->getData('id')]['items'][$item->getData('id')] = $item->getData();
	        			}
	        		}
                    // 过滤规格为空的规格组
                    if(!isset($mall_goods_specs[$cat->getData('id')]['groups'][$group->getData('id')]['items']) || count($mall_goods_specs[$cat->getData('id')]['groups'][$group->getData('id')]['items'])<1){
                        unset($mall_goods_specs[$cat->getData('id')]['groups'][$group->getData('id')]);
                    }
        		}
        	}
            // 过滤规格为空的规格组
            if(!isset($mall_goods_specs[$cat->getData('id')]['groups']) || count($mall_goods_specs[$cat->getData('id')]['groups'])<1){
                unset($mall_goods_specs[$cat->getData('id')]);
            }
        }
        // 单独缓存每个规格分类
        foreach ($mall_goods_specs as $key => $value) {
            if($value){
                cache('mall_goods_spec_cat_'.$key, $value);
            }
        }
        // 缓存所有规格分类
        cache('mall_goods_specs', $mall_goods_specs);
    }
}